package com.ics.cmsadmin.frame.utils;

import com.ics.cmsadmin.frame.profit.ProfitTypeEnum;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.util.Map;
import java.util.Optional;
import java.util.function.Predicate;

/**
 * 工具类
 */
public final class Tools {
    public final static Predicate<String> TRUE_PREDICATE = item -> true;
    public final static Predicate<String> LessThan100_PREDICATE = Tools::isLessThan100;
    public final static Predicate<String> AGENT_SHARE_RATE_PREDICATE = Tools::agentShareRateValid;
    public final static Predicate<String> NUMERIC_PREDICATE = Tools::isNumeric;
    public final static Predicate<String> INTEGER_PREDICATE = Tools::isInteger;

    /**
     * 判断字符串是否为数字
     * @param value
     * @return
     */
    public static boolean isNumeric(String value){
        if (StringUtils.isBlank(value)){
            return false;
        }
        return value.matches("^[-\\+]?([1-9]\\d*|0)(\\.\\d+)?$");
    }

    /**
     * 代理商分润比例校验规则
     */
    public static boolean agentShareRateValid(String value){
        try {
            ProfitTypeEnum.GRADIENT_RATE.getFactory().verifyExpression(value);
            return true;
        }catch (Exception e){
            return false;
        }
    }
    /**
     * 少于100的
     * @param value
     * @return
     */
    public static boolean isLessThan100(String value){
        try {
            BigDecimal bigDecimal = new BigDecimal(value);
            if (bigDecimal.compareTo(new BigDecimal(100)) > 0){
                return false;
            }
            return true;
        }catch (Exception e){
            return false;
        }
    }
    /**
     * 判断字符串是否为整数
     */
    public static boolean isInteger(String value){
        if (StringUtils.isBlank(value)) {
            return false;
        }
        try {
            Integer.valueOf(value);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    /**
     * 生成随机code
     */
    public static String randomString(int count){
        if (count <= 0){
            count = 4;
        }
        return RandomStringUtils.random(count, "123456789QWERTYUIOPLKJHGFDSAZXCVBNMqwertyuioplkjhgfdsazxcvbnm");
    }

    public static String getValueFromMap(Map<String, Object> map, String key) {
        if (map == null){
            return "";
        }
        return Optional.ofNullable(map.get(key)).orElse("").toString();
    }
}
